package loader.puller;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

public class FilePuller {
	private byte[] getXmlBuffer(String strUrl) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {

			URL url = new URL(strUrl);
			HttpURLConnection httpUrl = (HttpURLConnection) url
					.openConnection();

			Properties prop = System.getProperties();
			prop.setProperty("http.proxyHost", "10.132.145.24");
			prop.setProperty("http.proxyPort", "808");

			httpUrl.connect();
			BufferedInputStream bis = new BufferedInputStream(
					httpUrl.getInputStream());

			byte[] buf = new byte[1024];
			while (true) {
				int bytes_read = bis.read(buf);
				if (bytes_read > 0) {
					bos.write(buf, 0, bytes_read);
				} else {
					break;
				}
			}
			bis.close();
			httpUrl.disconnect();
		} catch (Exception e) {
			System.out.println("ERROR!\n" + e);
			return null;
		}
		return bos.toByteArray();
	}

	public void pull(String url, String dir) {
		try {
			byte[] strBuf = getXmlBuffer(url);
			File file = new File(dir);
			FileOutputStream fileStream = new FileOutputStream(file);
			fileStream.write(strBuf);
			fileStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		FilePuller puller = new FilePuller();
		puller.pull("http://www.meituan.com/api/v2/beijing/deals",
				"E:/deals.xml");
	}
}